package cn.lingyangwl.agile.common.security.config;

import cn.lingyangwl.agile.model.constants.*;
import cn.lingyangwl.agile.model.module.auth.*;
import cn.lingyangwl.agile.model.module.tenant.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
public class WebSocketSecurityConfig extends ServerEndpointConfig.Configurator {

    /**
     * 建立握手时，连接前的操作
     */
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        // 这个userProperties 可以通过 session.getUserProperties( )获取
        final Map<String, Object> userProperties = sec.getUserProperties();
        Map<String, List<String>> headers = request.getHeaders();

        // 从请求头中拿到用户信息
        LoginUser loginUser = LoginUser.decode(headers.get(RequestCons.Headers.LOGIN_USER).stream().findFirst().orElse(""));

        if (Objects.nonNull(loginUser)) {
            TenantContext.get().setTenant(loginUser.getTenant());
            userProperties.put(LoginUser.class.getSimpleName(), loginUser);
        }
    }

    /**
     * 初始化端点对象,也就是被@ServerEndpoint所标注的对象
     */
    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return super.getEndpointInstance(clazz);
    }
}
